package com.ruoyi.mobile.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.UUIDgen;
import com.ruoyi.common.security.utils.DictUtils;
import com.ruoyi.mobile.domain.*;
import com.ruoyi.mobile.mapper.*;
import com.ruoyi.mobile.service.IShOrderService;
import com.ruoyi.mobile.service.MaterialService;
import com.ruoyi.mobile.utils.NftResponse;
import com.ruoyi.mobile.utils.Paginator;
import com.ruoyi.mobile.utils.QueryUtil;
import com.ruoyi.mobile.utils.ResponseConstants;
import com.ruoyi.system.api.domain.SysDictData;
import com.ruoyi.system.api.req.*;
import com.ruoyi.system.api.resp.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class MaterialServiceImpl extends ServiceImpl<MaterialInfoMapper, MaterialInfoEntity> implements MaterialService {
    @Resource
    private StringRedisTemplate myRedisTemplate;
    @Autowired
    private IShProductMapper productMapper;
    @Autowired
    private IShOrderService shOrderService;
    @Autowired
    private MaterialOrderMapper orderMapper;
    @Autowired
    private MaterialCollectMapper collectMapper;
    @Autowired
    private MaterialDownMapper downMapper;
    @Autowired
    private MaterialViewMapper viewMapper;
    @Autowired
    private ISysUserMapper sysUserMapper;

    @Override
    public NftResponse<List<DictResp>> getGrades() {
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("GRADE");
        List<DictResp> listResult = new ArrayList<>();
        if (mapValue.isEmpty()) {
            List<DictResp> dictList = productMapper.selectDictByType("grade");
            mapValue = new HashMap<>();
            for (DictResp obj:dictList) {
                listResult.add(obj);
            }
            myRedisTemplate.opsForHash().putAll("GRADE", mapValue);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                DictResp resp = JSON.parseObject(entry.getValue().toString().replaceAll("\\\\",""), DictResp.class);
                listResult.add(resp);
            }
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", listResult);
    }

    @Override
    public NftResponse<List<DictResp>> getSubjects() {
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("SUBJECT");
        List<DictResp> listResult = new ArrayList<>();
        if (mapValue.isEmpty()) {
            List<DictResp> dictList = productMapper.selectDictByType("subject");
            mapValue = new HashMap<>();
            for (DictResp obj:dictList) {
                listResult.add(obj);
            }
            myRedisTemplate.opsForHash().putAll("SUBJECT", mapValue);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                DictResp resp = JSON.parseObject(entry.getValue().toString().replaceAll("\\\\",""), DictResp.class);
                listResult.add(resp);
            }
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", listResult);
    }

    @Override
    public NftResponse<List<DictResp>> getSemesters() {
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("SEMESTER");
        List<DictResp> listResult = new ArrayList<>();
        if (mapValue.isEmpty()) {
            List<DictResp> dictList = productMapper.selectDictByType("semester");
            mapValue = new HashMap<>();
            for (DictResp obj:dictList) {
                listResult.add(obj);
            }
            myRedisTemplate.opsForHash().putAll("SEMESTER", mapValue);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                DictResp resp = JSON.parseObject(entry.getValue().toString().replaceAll("\\\\",""), DictResp.class);
                listResult.add(resp);
            }
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", listResult);
    }

    @Override
    public NftResponse<List<Integer>> getAges() {
        Calendar cal = Calendar.getInstance();
        int currentYear = cal.get(Calendar.YEAR);
        List<Integer> list = new ArrayList<>();
        list.add(currentYear);
        for (int i = 1; i <= 20; i++) {
            int previousYear = currentYear - i;
            list.add(previousYear);
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", list);
    }

    @Override
    public NftResponse<Paginator<MaterialInfoResp>> getMaterialList(MaterialInfoReq query) {
        if (query.getPageNo() == null || query.getPageNo() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参页码错误", null);
        }
        if (query.getPageSize() == null || query.getPageSize() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参每页数量错误", null);
        }
        List<SysDictData> dictGList = DictUtils.getDictCache("grade");
        List<SysDictData> dictSList = DictUtils.getDictCache("subject");
        List<SysDictData> dictMList = DictUtils.getDictCache("semester");
        HashMap<String, String> dictGMap = new HashMap<>();
        HashMap<String, String> dictSMap = new HashMap<>();
        HashMap<String, String> dictMMap = new HashMap<>();
        for (SysDictData data:dictGList) {
            dictGMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictSList) {
            dictSMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictMList) {
            dictMMap.put(data.getDictValue(),data.getDictLabel());
        }
        Paginator<MaterialInfoResp> paginator = new Paginator<MaterialInfoResp>(query.getPageNo(), query.getPageSize(), 0, new ArrayList<>());
        QueryWrapper<MaterialInfoEntity> wrapperQuery = new QueryWrapper<>();
        if (null!=query.getGrade()&&query.getGrade()>0) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("grade"), query.getGrade());
        }
        if (null!=query.getSubject()&&query.getSubject()>0) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("subject"), query.getSubject());
        }
        if (null!=query.getSemester()&&query.getSemester()>0) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("semester"), query.getSemester());
        }
        if (null!=query.getAge()&&query.getAge()>0) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("age"), query.getAge());
        }
        if (null!=query.getAppid()&&!"".equals(query.getAppid())) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("appId"),query.getAppid());
        }
        if (null!=query.getCollection()&&!"".equals(query.getCollection())) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("collection"), query.getCollection());
        }
        if (null!=query.getMaterialName()&&!"".equals(query.getMaterialName())) {
            wrapperQuery.like(QueryUtil.camelToUnderline("materialName"), query.getMaterialName());
        }
        if ("1".equals(query.getPxType())) {
            wrapperQuery.orderByDesc("create_time");
        }else if ("2".equals(query.getPxType())) {
            List<String> colList = new ArrayList<>();
            colList.add("down_num");
            colList.add("read_num");
            wrapperQuery.orderByDesc(colList);
        }
        IPage<MaterialInfoEntity> page = new Page<>(query.getPageNo(),query.getPageSize());
        IPage<MaterialInfoEntity> pageRtn = this.baseMapper.selectPage(page,wrapperQuery);
        List<MaterialInfoEntity> list = pageRtn.getRecords();
        List<MaterialInfoResp> result = BeanUtil.copyToList(list, MaterialInfoResp.class);
        for (MaterialInfoResp obj:result) {
            obj.setGradeName(dictGMap.get(obj.getGrade()+""));
            obj.setSubjectName(dictSMap.get(obj.getSubject()+""));
            obj.setSemesterName(dictMMap.get(obj.getSemester()+""));
        }
        paginator.setPageNo(query.getPageNo());
        paginator.setPageSize(query.getPageSize());
        paginator.setTotalDataNum(pageRtn.getTotal());
        paginator.setPageData(result);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", paginator);
    }

    @Override
    public NftResponse<Paginator<MaterialOrderResp>> getOrderList(MaterialOrderReq query) {
        if (query.getPageNo() == null || query.getPageNo() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参页码错误", null);
        }
        if (query.getPageSize() == null || query.getPageSize() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参每页数量错误", null);
        }
        List<SysDictData> dictGList = DictUtils.getDictCache("grade");
        List<SysDictData> dictSList = DictUtils.getDictCache("subject");
        List<SysDictData> dictMList = DictUtils.getDictCache("semester");
        HashMap<String, String> dictGMap = new HashMap<>();
        HashMap<String, String> dictSMap = new HashMap<>();
        HashMap<String, String> dictMMap = new HashMap<>();
        for (SysDictData data:dictGList) {
            dictGMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictSList) {
            dictSMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictMList) {
            dictMMap.put(data.getDictValue(),data.getDictLabel());
        }
        Paginator<MaterialOrderResp> paginator = new Paginator<MaterialOrderResp>(query.getPageNo(), query.getPageSize(), 0, new ArrayList<>());
        QueryWrapper<MaterialOrderEntity> wrapperQuery = new QueryWrapper<>();
        if (null!=query.getUserId()&&query.getUserId()>0) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("userId"), query.getUserId());
        }
        if (null!=query.getAppid()&&!"".equals(query.getAppid())) {
            wrapperQuery.inSql("material_id", "select id from material_info where app_id='"+query.getAppid()+"'");
        }
        wrapperQuery.eq(QueryUtil.camelToUnderline("status"), 1);
        IPage<MaterialOrderEntity> page = new Page<>(query.getPageNo(),query.getPageSize());
        IPage<MaterialOrderEntity> pageRtn = orderMapper.selectPage(page,wrapperQuery);
        List<MaterialOrderEntity> list = pageRtn.getRecords();
        List<MaterialOrderResp> result = BeanUtil.copyToList(list, MaterialOrderResp.class);
        for (MaterialOrderResp obj:result) {
            MaterialInfoEntity entity = this.baseMapper.selectById(obj.getMaterialId());
            if (null!=entity) {
                obj.setMaterialName(entity.getAge() +
                        dictGMap.get(entity.getGrade() + "") +
                        dictMMap.get(entity.getSemester() + "") +
                        entity.getMaterialName());
            }
        }
        paginator.setPageNo(query.getPageNo());
        paginator.setPageSize(query.getPageSize());
        paginator.setTotalDataNum(pageRtn.getTotal());
        paginator.setPageData(result);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", paginator);
    }

    @Override
    public NftResponse<Paginator<MaterialDownResp>> getDownList(MaterialDownReq query) {
        if (query.getPageNo() == null || query.getPageNo() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参页码错误", null);
        }
        if (query.getPageSize() == null || query.getPageSize() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参每页数量错误", null);
        }
        List<SysDictData> dictGList = DictUtils.getDictCache("grade");
        List<SysDictData> dictSList = DictUtils.getDictCache("subject");
        List<SysDictData> dictMList = DictUtils.getDictCache("semester");
        HashMap<String, String> dictGMap = new HashMap<>();
        HashMap<String, String> dictSMap = new HashMap<>();
        HashMap<String, String> dictMMap = new HashMap<>();
        for (SysDictData data:dictGList) {
            dictGMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictSList) {
            dictSMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictMList) {
            dictMMap.put(data.getDictValue(),data.getDictLabel());
        }
        Paginator<MaterialDownResp> paginator = new Paginator<MaterialDownResp>(query.getPageNo(), query.getPageSize(), 0, new ArrayList<>());
        QueryWrapper<MaterialDownEntity> wrapperQuery = new QueryWrapper<>();
        if (null!=query.getUserId()&&query.getUserId()>0) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("userId"), query.getUserId());
        }
        if (null!=query.getAppid()&&!"".equals(query.getAppid())) {
            wrapperQuery.inSql("material_id", "select id from material_info where app_id='"+query.getAppid()+"'");
        }
        IPage<MaterialDownEntity> page = new Page<>(query.getPageNo(),query.getPageSize());
        IPage<MaterialDownEntity> pageRtn = downMapper.selectPage(page,wrapperQuery);
        List<MaterialDownEntity> list = pageRtn.getRecords();
        List<MaterialDownResp> result = BeanUtil.copyToList(list, MaterialDownResp.class);
        for (MaterialDownResp obj:result) {
            MaterialInfoEntity entity = this.baseMapper.selectById(obj.getMaterialId());
            if (null!=entity) {
                obj.setMaterialName(entity.getAge() +
                        dictGMap.get(entity.getGrade() + "") +
                        dictMMap.get(entity.getSemester() + "") +
                        entity.getMaterialName());
            }
        }
        paginator.setPageNo(query.getPageNo());
        paginator.setPageSize(query.getPageSize());
        paginator.setTotalDataNum(pageRtn.getTotal());
        paginator.setPageData(result);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", paginator);
    }

    @Override
    public NftResponse<Paginator<MaterialViewResp>> getViewList(MaterialViewReq query) {
        if (query.getPageNo() == null || query.getPageNo() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参页码错误", null);
        }
        if (query.getPageSize() == null || query.getPageSize() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参每页数量错误", null);
        }
        List<SysDictData> dictGList = DictUtils.getDictCache("grade");
        List<SysDictData> dictSList = DictUtils.getDictCache("subject");
        List<SysDictData> dictMList = DictUtils.getDictCache("semester");
        HashMap<String, String> dictGMap = new HashMap<>();
        HashMap<String, String> dictSMap = new HashMap<>();
        HashMap<String, String> dictMMap = new HashMap<>();
        for (SysDictData data:dictGList) {
            dictGMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictSList) {
            dictSMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictMList) {
            dictMMap.put(data.getDictValue(),data.getDictLabel());
        }
        Paginator<MaterialViewResp> paginator = new Paginator<MaterialViewResp>(query.getPageNo(), query.getPageSize(), 0, new ArrayList<>());
        QueryWrapper<MaterialViewEntity> wrapperQuery = new QueryWrapper<>();
        if (null!=query.getUserId()&&query.getUserId()>0) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("userId"), query.getUserId());
        }
        if (null!=query.getAppid()&&!"".equals(query.getAppid())) {
            wrapperQuery.inSql("material_id", "select id from material_info where app_id='"+query.getAppid()+"'");
        }
        IPage<MaterialViewEntity> page = new Page<>(query.getPageNo(),query.getPageSize());
        IPage<MaterialViewEntity> pageRtn = viewMapper.selectPage(page,wrapperQuery);
        List<MaterialViewEntity> list = pageRtn.getRecords();
        List<MaterialViewResp> result = BeanUtil.copyToList(list, MaterialViewResp.class);
        for (MaterialViewResp obj:result) {
            MaterialInfoEntity entity = this.baseMapper.selectById(obj.getMaterialId());
            if (null!=entity) {
                obj.setMaterialName(entity.getAge() +
                        dictGMap.get(entity.getGrade() + "") +
                        dictMMap.get(entity.getSemester() + "") +
                        entity.getMaterialName());
            }
        }
        paginator.setPageNo(query.getPageNo());
        paginator.setPageSize(query.getPageSize());
        paginator.setTotalDataNum(pageRtn.getTotal());
        paginator.setPageData(result);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", paginator);
    }

    @Override
    public NftResponse<Paginator<MaterialCollectResp>> getCollectList(MaterialCollectReq query) {
        if (query.getPageNo() == null || query.getPageNo() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参页码错误", null);
        }
        if (query.getPageSize() == null || query.getPageSize() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参每页数量错误", null);
        }
        List<SysDictData> dictGList = DictUtils.getDictCache("grade");
        List<SysDictData> dictSList = DictUtils.getDictCache("subject");
        List<SysDictData> dictMList = DictUtils.getDictCache("semester");
        HashMap<String, String> dictGMap = new HashMap<>();
        HashMap<String, String> dictSMap = new HashMap<>();
        HashMap<String, String> dictMMap = new HashMap<>();
        for (SysDictData data:dictGList) {
            dictGMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictSList) {
            dictSMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictMList) {
            dictMMap.put(data.getDictValue(),data.getDictLabel());
        }
        Paginator<MaterialCollectResp> paginator = new Paginator<MaterialCollectResp>(query.getPageNo(), query.getPageSize(), 0, new ArrayList<>());
        QueryWrapper<MaterialCollectEntity> wrapperQuery = new QueryWrapper<>();
        if (null!=query.getUserId()&&query.getUserId()>0) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("userId"), query.getUserId());
        }
        if (null!=query.getAppid()&&!"".equals(query.getAppid())) {
            wrapperQuery.inSql("material_id", "select id from material_info where app_id='"+query.getAppid()+"'");
        }
        IPage<MaterialCollectEntity> page = new Page<>(query.getPageNo(),query.getPageSize());
        IPage<MaterialCollectEntity> pageRtn = collectMapper.selectPage(page,wrapperQuery);
        List<MaterialCollectEntity> list = pageRtn.getRecords();
        List<MaterialCollectResp> result = BeanUtil.copyToList(list, MaterialCollectResp.class);
        for (MaterialCollectResp obj:result) {
            MaterialInfoEntity entity = this.baseMapper.selectById(obj.getMaterialId());
            if (null!=entity) {
                obj.setMaterialName(entity.getAge() +
                        dictGMap.get(entity.getGrade() + "") +
                        dictMMap.get(entity.getSemester() + "") +
                        entity.getMaterialName());
            }
        }
        paginator.setPageNo(query.getPageNo());
        paginator.setPageSize(query.getPageSize());
        paginator.setTotalDataNum(pageRtn.getTotal());
        paginator.setPageData(result);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", paginator);
    }

    @Override
    public NftResponse<MaterialInfoResp> getMaterialInfo(Long id, Long userId) {
        List<SysDictData> dictGList = DictUtils.getDictCache("grade");
        List<SysDictData> dictSList = DictUtils.getDictCache("subject");
        List<SysDictData> dictMList = DictUtils.getDictCache("semester");
        HashMap<String, String> dictGMap = new HashMap<>();
        HashMap<String, String> dictSMap = new HashMap<>();
        HashMap<String, String> dictMMap = new HashMap<>();
        for (SysDictData data:dictGList) {
            dictGMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictSList) {
            dictSMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictMList) {
            dictMMap.put(data.getDictValue(),data.getDictLabel());
        }
        MaterialInfoEntity entity = this.baseMapper.selectById(id);
        MaterialInfoResp rtn = BeanUtil.copyProperties(entity, MaterialInfoResp.class);
        rtn.setGradeName(dictGMap.get(rtn.getGrade()+""));
        rtn.setSubjectName(dictSMap.get(rtn.getSubject()+""));
        rtn.setSemesterName(dictMMap.get(rtn.getSemester()+""));
        QueryWrapper<MaterialOrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(QueryUtil.camelToUnderline("materialId"), id);
        wrapper.eq(QueryUtil.camelToUnderline("userId"), userId);
        List<MaterialOrderEntity> orderList = orderMapper.selectList(wrapper);
        if (null!=orderList&&orderList.size()>0) {
            rtn.setPay(true);
        }else {
            rtn.setPay(false);
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", rtn);
    }

    @Override
    public NftResponse<JSONObject> insertOrderInfo(MaterialOrderReq query) {
        if (null == query.getMaterialId() || query.getMaterialId() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "请输入下单资料", null);
        }
        if (null == query.getAmount() || query.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "请输入订单金额", null);
        }
        QueryWrapper<MaterialOrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(QueryUtil.camelToUnderline("materialId"), query.getMaterialId());
        wrapper.eq(QueryUtil.camelToUnderline("userId"), query.getUserId());
        List<MaterialOrderEntity> orderList = orderMapper.selectList(wrapper);
        if (null!=orderList&&orderList.size()>0) {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "重复下单", null);
        }else {
            SysUserEntity sysUser = sysUserMapper.selectById(query.getUserId());
            String orderNo = UUIDgen.getUUID(20);
            MaterialOrderEntity entity = BeanUtil.copyProperties(query, MaterialOrderEntity.class);
            entity.setOrderNo(orderNo);
            entity.setUsername(sysUser.getUserName());
            entity.setUserphone(sysUser.getPhonenumber());
            entity.setCreateTime(DateUtils.getNowDate());
            orderMapper.insert(entity);
            BigDecimal fee = query.getAmount().multiply(BigDecimal.valueOf(100));
            try {
                String appId = query.getAppid();
                NftResponse<JSONObject> rtn = shOrderService.wxPayFunction(appId, String.valueOf(fee.intValue()), orderNo, query.getUserId());
                return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "下单成功", rtn.getData());
            }catch (Exception e){}
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "下单成功", null);
        }
    }

    @Override
    public NftResponse<Boolean> insertDownInfo(MaterialDownReq query) {
        if (null == query.getMaterialId() || query.getMaterialId() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "请输入下单资料", null);
        }
        MaterialInfoEntity info = this.baseMapper.selectById(query.getMaterialId());
        QueryWrapper<MaterialOrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(QueryUtil.camelToUnderline("materialId"), query.getMaterialId());
        wrapper.eq(QueryUtil.camelToUnderline("userId"), query.getUserId());
        List<MaterialOrderEntity> orderList = orderMapper.selectList(wrapper);
        if (info.getIsFree()==1||(null!=orderList&&orderList.size()>0)) {
            QueryWrapper<MaterialDownEntity> wrapperD = new QueryWrapper<>();
            wrapperD.eq(QueryUtil.camelToUnderline("materialId"), query.getMaterialId());
            wrapperD.eq(QueryUtil.camelToUnderline("userId"), query.getUserId());
            List<MaterialDownEntity> downList = downMapper.selectList(wrapperD);
            if (null!=downList&&downList.size()>0) {
                return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "重复下载", false);
            }else {
                QueryWrapper<MaterialDownEntity> wrapperDD = new QueryWrapper<>();
                wrapperDD.eq(QueryUtil.camelToUnderline("userId"), query.getUserId());
                Date today = DateUtils.getNowDate();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                String todayStr = formatter.format(today);
                wrapperDD.apply(StringUtils.isNotBlank(todayStr),"DATE(create_time) = STR_TO_DATE('"+todayStr+"','%Y-%m-%d')");
                List<MaterialDownEntity> downDList = downMapper.selectList(wrapperDD);
                if (info.getIsFree()==1&&null!=downDList&&downDList.size()>=2) {
                    return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "您已达到每日2次免费下载限制", false);
                }else {
                    SysUserEntity sysUser = sysUserMapper.selectById(query.getUserId());
                    MaterialDownEntity entity = BeanUtil.copyProperties(query, MaterialDownEntity.class);
                    entity.setUsername(sysUser.getUserName());
                    entity.setUserphone(sysUser.getPhonenumber());
                    entity.setCreateTime(DateUtils.getNowDate());
                    downMapper.insert(entity);
                    QueryWrapper<MaterialDownEntity> wrapperQuery = new QueryWrapper<>();
                    wrapperQuery.eq(QueryUtil.camelToUnderline("materialId"), query.getMaterialId());
                    Long downNum = downMapper.selectCount(wrapperQuery);
                    info.setDownNum(downNum);
                    this.baseMapper.updateById(info);
                    return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "下载成功", true);
                }
            }
        }else {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "不允许下载", false);
        }
    }

    @Override
    public NftResponse<JSONObject> insertCollectInfo(MaterialCollectReq query) {
        if (null == query.getMaterialId() || query.getMaterialId() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "请输入下单资料", null);
        }
        QueryWrapper<MaterialCollectEntity> wrapperC = new QueryWrapper<>();
        wrapperC.eq(QueryUtil.camelToUnderline("material_id"), query.getMaterialId());
        wrapperC.eq(QueryUtil.camelToUnderline("user_id"), query.getUserId());
        List<MaterialCollectEntity> collectList = collectMapper.selectList(wrapperC);
        if (null!=collectList&&collectList.size()>0) {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "重复收藏", null);
        }else {
            SysUserEntity sysUser = sysUserMapper.selectById(query.getUserId());
            MaterialCollectEntity entity = BeanUtil.copyProperties(query, MaterialCollectEntity.class);
            entity.setUsername(sysUser.getUserName());
            entity.setUserphone(sysUser.getPhonenumber());
            entity.setCreateTime(DateUtils.getNowDate());
            collectMapper.insert(entity);
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "收藏成功", null);
        }
    }

    @Override
    public NftResponse<JSONObject> insertViewInfo(MaterialViewReq query) {
        if (null == query.getMaterialId() || query.getMaterialId() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "请输入下单资料", null);
        }
        QueryWrapper<MaterialViewEntity> wrapperV = new QueryWrapper<>();
        wrapperV.eq(QueryUtil.camelToUnderline("material_id"), query.getMaterialId());
        wrapperV.eq(QueryUtil.camelToUnderline("user_id"), query.getUserId());
        List<MaterialViewEntity> viewList = viewMapper.selectList(wrapperV);
        if (null==viewList||viewList.size()<=0) {
            SysUserEntity sysUser = sysUserMapper.selectById(query.getUserId());
            MaterialViewEntity entity = BeanUtil.copyProperties(query, MaterialViewEntity.class);
            entity.setUsername(sysUser.getUserName());
            entity.setUserphone(sysUser.getPhonenumber());
            entity.setCreateTime(DateUtils.getNowDate());
            viewMapper.insert(entity);
            MaterialInfoEntity info = this.baseMapper.selectById(query.getMaterialId());
            QueryWrapper<MaterialViewEntity> wrapperQuery = new QueryWrapper<>();
            wrapperQuery.eq(QueryUtil.camelToUnderline("materialId"), query.getMaterialId());
            Long readNum = viewMapper.selectCount(wrapperQuery);
            info.setReadNum(readNum);
            this.baseMapper.updateById(info);
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "浏览成功", null);
    }

    @Override
    public NftResponse<Boolean> delOrderzl(Long id) {
        int rtn = orderMapper.deleteById(id);
        if (rtn>0) {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "删除成功", true);
        }else {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "删除成功", false);
        }
    }

    @Override
    public NftResponse<Boolean> delDownzl(Long id) {
        int rtn = downMapper.deleteById(id);
        if (rtn>0) {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "删除成功", true);
        }else {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "删除成功", false);
        }
    }

    @Override
    public NftResponse<Boolean> delCollectzl(Long id) {
        int rtn = collectMapper.deleteById(id);
        if (rtn>0) {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "删除成功", true);
        }else {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "删除成功", false);
        }
    }

    @Override
    public NftResponse<Boolean> delViewzl(Long id) {
        int rtn = viewMapper.deleteById(id);
        if (rtn>0) {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "删除成功", true);
        }else {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "删除成功", false);
        }
    }
}
